
import sleep from '../utils/sleep';

type Params = WechatMiniprogram.RequestOption;
type Response = Promise<WechatMiniprogram.RequestSuccessCallbackResult<any>>;
const whiteList = ['/login'];
// const baseUrl = 'http://192.168.10.149:3000';
const baseUrl = 'https://dingshaohua.cn/openai';

export default async (params: Params): Response => {
    const isWhite = whiteList.some(it => params.url.indexOf(it) > -1);
    const token = wx.getStorageSync('token');
    params.url = baseUrl+params.url;
    // 如果不是白名单 还 没有token 让他登录
    if (!isWhite && !token) {
        wx.showToast({
            title: '登录过期',
            icon: 'error',
            mask: true,
            duration: 20000
        })
        await sleep(2000);
        wx.redirectTo({ url: '/pages/login/index' })
        return Promise.reject('登录过期');
    } else {
        return new Promise((resolve, reject) => {
            wx.request({
                ...params,
                header: {
                    token
                },
                success: (result) => {
                    if(result.statusCode === 401){
                        wx.redirectTo({ url: '/pages/login/index' })
                    }
                    resolve(result)
                },
                fail: (err) => { reject(err) },
            })
        });
    }
}